/* Team 2
   CS513
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>

const char *PORT="7766"; // unused port

int main(int argc, char **argv){
	struct addrinfo info, *res;
	int sock;
	// first, load up address structs with getaddrinfo():
	memset(&info, 0, sizeof info); // inialize to 0
	info.ai_family = AF_INET;  // use IPv4
	info.ai_socktype = SOCK_STREAM; // TCP
	info.ai_flags = AI_PASSIVE;     // fill in my IP for me
	int status=getaddrinfo(NULL, PORT, &info, &res); // get info for me (server) and store in res
	if(status!=0){
		fprintf(stderr, "Error with getaddrinfo: %s\n", gai_strerror(status));
		exit(1);
	}

	// make a socket for accepting clients
	sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
	if(sock<=0){
		fprintf(stderr,"Error creating socket\n");
		exit(1);
	}

	// bind it to the port we passed in to getaddrinfo():
	if(bind(sock, res->ai_addr, res->ai_addrlen)==-1){
		close(sock);
		perror("Bind failed");
		exit(1);
	}
	if(listen(sock, 5) == -1){
		perror("Listen failed");
		exit(1);
	}
	printf("Now accepting connections\n");

	int client_sock;
	struct sockaddr_storage client;
	socklen_t sin_size;


	while(1){ // really only once
		sin_size = sizeof client;
		client_sock = accept(sock, (struct sockaddr *)&client, &sin_size);
		if (client_sock == -1) {
			perror("accept");
			exit(1);
		}

		int flag=0;

		while(1){ // this trusts client code that no more than 5 messages will be sent
			//server code

		}


	}
}

